<template>
  <div class="product-detail-container">
    <!-- 头部导航 -->
    <Header />

    <div v-if="loading" class="loading">
      <div class="spinner"></div>
      加载中...
    </div>

    <div v-else-if="error" class="error-message">
      <div class="error-icon">⚠️</div>
      <div class="error-text">{{ error }}</div>
      <button class="retry-btn" @click="fetchProduct">重试</button>
    </div>

    <div v-else-if="product" class="product-content">
      <!-- 商品图片展示 -->
      <div class="product-gallery">
        <div class="main-image">
          <img :src="product.productImg || require('@/assets/product-default.png')" :alt="product.productName" />
        </div>
      </div>

      <!-- 商品信息 -->
      <div class="product-info">
        <h1 class="product-title">{{ product.productName }}</h1>

        <div class="product-meta">
          <span class="sales">销量: {{ product.sales || 0 }}</span>
          <span v-if="product.isHot === 1" class="hot-tag">热销</span>
        </div>

        <div class="price-section">
          <span class="current-price">¥{{ formatPrice(product.sellingPrice) }}</span>
          <span v-if="product.originalPrice" class="original-price">¥{{ formatPrice(product.originalPrice) }}</span>
        </div>

        <div class="product-desc" v-html="product.productDesc"></div>

        <!-- 数量选择 -->
        <div class="quantity-selector">
          <span class="label">数量:</span>
          <button class="quantity-btn" @click="decreaseQuantity" :disabled="quantity <= 1">-</button>
          <input type="number" v-model.number="quantity" min="1" :max="product.stock" class="quantity-input" />
          <button class="quantity-btn" @click="increaseQuantity" :disabled="quantity >= product.stock">+</button>
          <span class="stock">库存: {{ product.stock }}件</span>
        </div>

        <!-- 操作按钮 -->
        <div class="action-buttons">
          <button class="add-to-cart-btn" @click="addToCart">加入购物车</button>
          <button class="buy-now-btn" @click="buyNow">立即购买</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue';
import { useStore } from 'vuex';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import request from '../../utils/request';
import Header from '@/components/Header.vue';
import { addToCart as addToCartAPI } from '@/api/cart';

// 响应式数据
const product = ref(null);
const loading = ref(false);
const error = ref(null);
const quantity = ref(1);

// 获取store、route和router
const store = useStore();
const route = useRoute();
const router = useRouter();

// 计算属性
const currentUser = computed(() => store.state.currentUser);
const productId = computed(() => route.params.id);

// 方法
const formatPrice = (price) => {
  const num = Number(price);
  return isNaN(num) ? '0.00' : num.toFixed(2);
};

const increaseQuantity = () => {
  if (quantity.value < product.value.stock) {
    quantity.value++;
  }
};

const decreaseQuantity = () => {
  if (quantity.value > 1) {
    quantity.value--;
  }
};

const fetchProduct = async () => {
  try {
    loading.value = true;
    error.value = null;

    console.log('Fetching product with ID:', productId.value);

    const response = await request.get(`/products/${productId.value}`);
    product.value = response.data;

    console.log('Product data received:', product.value);

    if (!product.value) {
      throw new Error('商品不存在');
    }
  } catch (error) {
    console.error('获取商品详情失败:', error);
    error.value = error.response?.data?.message || '获取商品详情失败，请稍后重试';
  } finally {
    loading.value = false;
  }
};

const addToCart = async () => {
  if (!currentUser.value) {
    router.push('/login');
    return;
  }

  try {
    // 使用购物车API
    const response = await addToCartAPI(
      currentUser.value.userId,
      product.value.productId,
      quantity.value
    );

    if (response.data.status === 'success') {
      ElMessage.success('已添加到购物车');

      // 刷新store中的购物车数据
      await store.dispatch('fetchCartItems');

      // 可选：延迟跳转到购物车页面
      setTimeout(() => {
        router.push('/cart');
      }, 1000);
    } else {
      throw new Error(response.data.message || '添加到购物车失败');
    }
  } catch (error) {
    console.error('添加到购物车失败:', error);
    let errorMessage = '添加到购物车失败';

    if (error.response?.data?.message) {
      errorMessage = error.response.data.message;
    } else if (error.message) {
      errorMessage = error.message;
    }

    ElMessage.error(errorMessage);
  }
};

const buyNow = async () => {
  if (!currentUser.value) {
    router.push('/login');
    return;
  }
  // 先添加到购物车
  await addToCart();
  // 跳转到购物车或结算页
  router.push('/cart');
};

// 生命周期
onMounted(() => {
  fetchProduct();
});

// 监听器
watch(productId, () => {
  fetchProduct();
});
</script>

<style scoped>
.product-detail-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.loading {
  padding: 2rem;
  text-align: center;
  color: #666;
  font-size: 1rem;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.spinner {
  border: 3px solid #f3f3f3;
  border-top: 3px solid #f5222d;
  border-radius: 50%;
  width: 30px;
  height: 30px;
  animation: spin 1s linear infinite;
  margin-bottom: 1rem;
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }

  100% {
    transform: rotate(360deg);
  }
}

.error-message {
  padding: 2rem;
  text-align: center;
  background-color: #fff1f0;
  border-radius: 8px;
  margin: 1rem 0;
}

.error-icon {
  font-size: 2rem;
  margin-bottom: 1rem;
}

.error-text {
  color: #f5222d;
  margin-bottom: 1rem;
}

.retry-btn {
  padding: 0.5rem 1.5rem;
  background-color: #f5222d;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.product-content {
  display: flex;
  flex-wrap: wrap;
  gap: 40px;
  margin-top: 20px;
}

.product-gallery {
  flex: 1;
  min-width: 300px;
}

.main-image {
  background: #f5f5f5;
  border-radius: 8px;
  overflow: hidden;
}

.main-image img {
  width: 100%;
  height: auto;
  display: block;
}

.product-info {
  flex: 1;
  min-width: 300px;
}

.product-title {
  font-size: 24px;
  color: #333;
  margin-bottom: 15px;
}

.product-meta {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  color: #666;
}

.sales {
  margin-right: 15px;
}

.hot-tag {
  background: #f5222d;
  color: white;
  padding: 3px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: bold;
}

.price-section {
  margin: 20px 0;
  padding: 15px 0;
  border-top: 1px solid #eee;
  border-bottom: 1px solid #eee;
}

.current-price {
  font-size: 28px;
  color: #f5222d;
  font-weight: bold;
  margin-right: 10px;
}

.original-price {
  font-size: 16px;
  color: #999;
  text-decoration: line-through;
}

.product-desc {
  margin: 20px 0;
  line-height: 1.6;
  color: #666;
}

.quantity-selector {
  display: flex;
  align-items: center;
  margin: 30px 0;
}

.label {
  margin-right: 15px;
  color: #666;
}

.quantity-btn {
  width: 30px;
  height: 30px;
  background: #f5f5f5;
  border: 1px solid #ddd;
  font-size: 16px;
  cursor: pointer;
}

.quantity-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.quantity-input {
  width: 50px;
  height: 30px;
  text-align: center;
  border: 1px solid #ddd;
  margin: 0 5px;
}

.stock {
  margin-left: 15px;
  color: #666;
}

.action-buttons {
  display: flex;
  gap: 15px;
  margin-top: 30px;
}

.add-to-cart-btn,
.buy-now-btn {
  padding: 12px 30px;
  border: none;
  border-radius: 4px;
  font-size: 16px;
  cursor: pointer;
  transition: all 0.3s;
}

.add-to-cart-btn {
  background-color: #ff9500;
  color: white;
}

.add-to-cart-btn:hover {
  background-color: #e68600;
}

.buy-now-btn {
  background-color: #f5222d;
  color: white;
}

.buy-now-btn:hover {
  background-color: #d32029;
}

@media (max-width: 768px) {
  .product-content {
    flex-direction: column;
  }

  .action-buttons {
    flex-direction: column;
  }

  .add-to-cart-btn,
  .buy-now-btn {
    width: 100%;
  }
}
</style>